package com.huawei.app.demo.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.app.demo.AppConstants;
import com.huawei.app.demo.MainActivity;
import com.huawei.app.demo.R;
import com.huawei.app.demo.task.StressTestTask;
import com.huawei.app.demo.util.CommonUtils;
import com.huawei.app.demo.util.LauncherUtils;
import com.huawei.app.demo.util.LogUtils;
import com.huawei.app.demo.util.SystemIconUtils;
import com.huawei.app.httpapi.ThreadPools;

/**
 * 基础功能
 *
 * @since 2021-01-20
 */
public class CommFragment extends CustomFragment {

    private static final String TAG = CommFragment.class.getSimpleName();
    private Context context;
    private View rootView;

    private TextView selectFileResult;
    private Button stressTestBtn;
    private CheckBox hideNinePoint;
    private CheckBox hideBackBtn;
    private CheckBox hideToolbar;

    private List<StressTestTask> stressTestTasks;

    @Override
    public String getTitle() {
        return "基础";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (this.rootView != null) {
            return rootView;
        }
        this.context = getContext();
        this.rootView = inflater.inflate(R.layout.fragment_comm, container, false);

        // init view
        Button openSetting = rootView.findViewById(R.id.openSetting);
        Button show4kImg = rootView.findViewById(R.id.show4kImg);
        Button selectFileBtn = rootView.findViewById(R.id.selectFileBtn);
        this.selectFileResult = rootView.findViewById(R.id.selectFileResult);
        this.stressTestBtn = rootView.findViewById(R.id.stressTestBtn);
        Button autoInstallBtn = rootView.findViewById(R.id.autoInstallBtn);
        this.hideNinePoint = rootView.findViewById(R.id.hideNinePoint);
        this.hideBackBtn = rootView.findViewById(R.id.hideBackBtn);
        this.hideToolbar = rootView.findViewById(R.id.hideToolbar);
        Button readThumbprintBtn = rootView.findViewById(R.id.readThumbprintBtn);
        Button setDefaultLauncherBtn = rootView.findViewById(R.id.setDefaultLauncherBtn);

        // init event
        openSetting.setOnClickListener(this);
        show4kImg.setOnClickListener(this);
        selectFileBtn.setOnClickListener(this);
        stressTestBtn.setOnClickListener(this);
        autoInstallBtn.setOnClickListener(this);
        hideNinePoint.setOnClickListener(this);
        hideBackBtn.setOnClickListener(this);
        hideToolbar.setOnClickListener(this);
        readThumbprintBtn.setOnClickListener(this);
        setDefaultLauncherBtn.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        switch (viewId) {
            case R.id.openSetting: {
                openSetting();
                break;
            }
            case R.id.show4kImg:
            case R.id.imgViewBackBtn : {
                show4kImg();
                break;
            }
            case R.id.selectFileBtn : {
                selectFile();
                break;
            }
            case R.id.stressTestBtn : {
                stressTest();
                break;
            }
            case R.id.autoInstallBtn : {
                autoInstall();
                break;
            }
            case R.id.hideNinePoint: {
                hideNinePoint();
                break;
            }
            case R.id.hideBackBtn: {
                hideBackBtn();
                break;
            }
            case R.id.hideToolbar: {
                hideToolbar();
                break;
            }
            case R.id.readThumbprintBtn : {
                readThumbprint();
                break;
            }
            case R.id.setDefaultLauncherBtn : {
                setDefaultLauncher();
                break;
            }
            default: {
                break;
            }
        }
    }

    public void openSetting() {
        LogUtils.getInstance().i(TAG, "openSetting begin.");

        Intent intent=new Intent(Settings.ACTION_SETTINGS);
        startActivity(intent);

        LogUtils.getInstance().i(TAG, "openSetting end.");
    }

    /**
     * 显示4k图片, 多次调用此方法时在显示/隐藏状态之间切换
     */
    public void show4kImg() {
        LogUtils.getInstance().i(TAG, "show4kImg begin.");
        LinearLayout mainPanel = getActivity().findViewById(R.id.mainPanel);
        if (mainPanel.getChildCount() > 0) {
            String firstViewId = getResources().getResourceName(mainPanel.getChildAt(0).getId());
            if (firstViewId != null && firstViewId.endsWith("img4kView")) {
                // 隐藏图片
                mainPanel.removeViewAt(0);
                LogUtils.getInstance().i(TAG, "show4kImg end, remove previous image.");
                return;
            }
        }

        // 显示图片
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.image_view, null);
        mainPanel.addView(view, 0);

        // 给返回按钮绑定事件
        Button backBtn = view.findViewById(R.id.imgViewBackBtn);
        backBtn.setOnClickListener(this);
        LogUtils.getInstance().i(TAG, "show4kImg end.");
    }

    /**
     * 选择文件
     */
    public void selectFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, AppConstants.REQUEST_SELECT_FILE_CODE);
    }

    /**
     * 压力测试
     */
    public void stressTest() {
        if (stressTestTasks != null && !stressTestTasks.isEmpty()) {
            for (StressTestTask task : stressTestTasks) {
                task.setRunning(false);
            }
            stressTestTasks.clear();
            stressTestTasks = null;
            stressTestBtn.setText("开始压力测试");
            return;
        }

        stressTestTasks = new ArrayList<>();
        for (int i=0; i<10; i++) {
            StressTestTask task = new StressTestTask("stressTest-" + i);
            stressTestTasks.add(task);
            ThreadPools.run(task);
        }
        stressTestBtn.setText("停止压力测试");
    }

    /**
     * 智能安装
     */
    public void autoInstall() {
        LogUtils.getInstance().i(TAG, "autoInstall begin.");

        // 检测智能辅助服务是否已开启
        if (!isAccessibilitySettingsOn(context)) {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivityForResult(intent, AppConstants.REQUEST_ENABLE_ACCESSIBILITY_SERVICES_CODE);
        } else {
            installApk();
        }

        LogUtils.getInstance().i(TAG, "autoInstall end.");
    }

    private void installApk() {
        // 安装应用
        String apkPath = "/sdcard/Download/test.apk";
        File apkFile = new File(apkPath);
        if (!apkFile.exists()) {
            Toast.makeText(context, "apk file [" + apkPath + "] not found.", Toast.LENGTH_LONG).show();
            LogUtils.getInstance().e(TAG, "installApk failed, apk file not found.");
            return;
        }
        Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public void hideNinePoint() {
        LogUtils.getInstance().i(TAG, "hideNinePoint begin.");

        SystemIconUtils.hideNinePoint(context, hideNinePoint.isChecked());

        LogUtils.getInstance().i(TAG, "hideNinePoint end.");
    }

    public void hideBackBtn() {
        LogUtils.getInstance().i(TAG, "hideBackBtn begin.");

        SystemIconUtils.hideBackBtn(context, hideBackBtn.isChecked());

        LogUtils.getInstance().i(TAG, "hideBackBtn end.");
    }

    public void hideToolbar() {
        LogUtils.getInstance().i(TAG, "hideToolbar begin.");

        SystemIconUtils.hideToolbar(context, hideToolbar.isChecked());

        LogUtils.getInstance().i(TAG, "hideToolbar end.");
    }

    public void readThumbprint() {
        LogUtils.getInstance().i(TAG, "readThumbprint begin.");

        // String pkgName = context.getPackageName();
        // 这里以 Open Camera 为例演示获取应用的指纹信息
        String pkgName = "net.sourceforge.opencamera";
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo packageInfo = manager.getPackageInfo(pkgName, PackageManager.GET_SIGNATURES);
            byte[] firstSignData = packageInfo.signatures[0].toByteArray();
            String sha1 = CommonUtils.getSHA1Str(firstSignData);
            Toast.makeText(getActivity(), sha1, Toast.LENGTH_LONG).show();
            LogUtils.getInstance().i(TAG, "pkgName: " + pkgName + ", thumbprint: " + sha1);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtils.getInstance().e(TAG, "readThumbprint failed", e);
        }

        LogUtils.getInstance().i(TAG, "readThumbprint end.");
    }

    public void setDefaultLauncher() {
        LogUtils.getInstance().i(TAG, "setDefaultLauncher begin.");

        String pkgName = context.getPackageName();
        String activityName = MainActivity.class.getName();
        LauncherUtils.setDefaultLauncher(context, pkgName, activityName);

        LogUtils.getInstance().i(TAG, "setDefaultLauncher end.");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppConstants.REQUEST_SELECT_FILE_CODE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            selectFileResult.setText(uri.toString());
        } else if (requestCode == AppConstants.REQUEST_ENABLE_ACCESSIBILITY_SERVICES_CODE) {
            installApk();
        }
    }

    /**
     * 检查智能辅助服务是否已开启
     * @param context
     * @return
     */
    public static boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            LogUtils.getInstance().e(TAG, e.getMessage());
        }
        if (accessibilityEnabled == 1) {
            String services = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            LogUtils.getInstance().i(TAG, "enabled_accessibility_services is " + services);
            if (services != null) {
                return services.contains(context.getPackageName());
            }
        }
        return false;
    }
}
